﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using CentralOffice.Admin.Data;
using ProcessTable = CentralOffice.Admin.Data.ApprovalProcessDataSet.ApprovalProcessDataTable;
using ProcessRow = CentralOffice.Admin.Data.ApprovalProcessDataSet.ApprovalProcessRow;
using StepTable = CentralOffice.Admin.Data.ApprovalStepDataSet.ApprovalStepDataTable;
using StepRow = CentralOffice.Admin.Data.ApprovalStepDataSet.ApprovalStepRow;
using Husb.Util;


namespace CentralOffice.WebClient.Admin.Flow
{
    public partial class ApprovalStepEdit : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {

                string id = HttpContext.Current.Request.QueryString["id"];
                string processId = HttpContext.Current.Request.QueryString["processid"];

                // 审批对象
                SiteUtil.PopulateListBox(ddlApprovalObject, SiteConstants.ApprovalObject, false);

                if (!String.IsNullOrEmpty(id))
                {
                    StepRow step = CentralOffice.Admin.BusinessActions.ApprovalStep.GetByIdFromCache(new Guid(id));
                    SetFields(step);

                    PopulateProcess(step.ApprovalObject);

                    ddlApprovalObject.SelectedValue = step.ApprovalObject.ToString();
                    ddlApprovalProcess.SelectedValue = step.ApprovalProcessId.ToString();
                }
                else
                {
                    if (!String.IsNullOrEmpty(processId))
                    {
                        ProcessRow process = CentralOffice.Admin.BusinessActions.ApprovalProcess.GetByIdFromCache(new Guid(processId));
                        PopulateProcess(process.ApprovalObject);
                        if (ddlApprovalProcess.Items.Count > 0)
                        {
                            ddlApprovalProcess.SelectedValue = processId;
                        }

                        ddlApprovalObject.SelectedValue = process.ApprovalObject.ToString();

                    }
                    else
                    {
                        PopulateProcess(Int32.Parse(ddlApprovalObject.SelectedItem.Value));
                    }
                }


                // 审批对象
                //SiteUtil.PopulateListBox(ddlApprovalObject, SiteConstants.ApprovalObject, false);
                // 审批流程
                

                // 


                //if (ddlApprovalProcess.SelectedItem != null)
                //{
                //    PopulateStep(new Guid(ddlApprovalProcess.SelectedItem.Value));
                //}

                //if (!String.IsNullOrEmpty(id))
                //{
                //    SetFields(id);

                //    StepRow step = CentralOffice.Admin.BusinessActions.ApprovalStep.GetByIdFromCache(new Guid(id));

                //    ProcessRow process2 = CentralOffice.Admin.BusinessActions.ApprovalProcess.GetByIdFromCache(step.ApprovalProcessId);
                //    PopulateProcess(process2.ApprovalObject);
                //    if (ddlApprovalProcess.Items.Count > 0)
                //    {
                //        ddlApprovalProcess.SelectedValue = processId;
                //    }


                //    ddlApprovalObject.SelectedValue = step.ApprovalObject.ToString();
                //}
                
            }
        }

        private void SetFields(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                StepRow step = CentralOffice.Admin.BusinessActions.ApprovalStep.GetByIdFromCache(new Guid(id));

                txtName.Text = step.Name;
                txtContent.Text = step.ApprovalContent;
                txtRoles.Text = step.ApprovalBy;
                txtStepOrder.Text = step.StepOrder.ToString();
                ddlApprovalObject.SelectedValue = step.ApprovalObject.ToString();
                if (ddlApprovalObject.SelectedItem != null && ddlApprovalProcess.Items.Count > 0)
                {
                    ddlApprovalProcess.SelectedValue = step.ApprovalProcessId.ToString();
                }
                //if (ddlApprovalProcess.SelectedItem != null && ddlPreviousStep.Items.Count > 0 && !step.IsPreviousStepIdNull())
                //{
                //    ddlPreviousStep.SelectedValue = step.PreviousStepId.ToString();
                //}

                //

                txtEmp.Value = step.IsApprovalByEmpNull() ? "" : step.ApprovalByEmp;
                txtEmpReadOnly.Value = step.IsApprovalByEmpNull() ? "" : step.ApprovalByEmp;

            }
        }

        private void SetFields(StepRow step)
        {
            //StepRow step = CentralOffice.Admin.BusinessActions.ApprovalStep.GetByIdFromCache(new Guid(id));

            txtName.Text = step.Name;
            txtContent.Text = step.ApprovalContent;
            txtRoles.Text = step.ApprovalBy;
            txtStepOrder.Text = step.StepOrder.ToString();
            ddlApprovalObject.SelectedValue = step.ApprovalObject.ToString();
            if (ddlApprovalObject.SelectedItem != null && ddlApprovalProcess.Items.Count > 0)
            {
                ddlApprovalProcess.SelectedValue = step.ApprovalProcessId.ToString();
            }
            //if (ddlApprovalProcess.SelectedItem != null && ddlPreviousStep.Items.Count > 0 && !step.IsPreviousStepIdNull())
            //{
            //    ddlPreviousStep.SelectedValue = step.PreviousStepId.ToString();
            //}
            txtEmp.Value = step.IsApprovalByEmpNull() ? "" : step.ApprovalByEmp;
            txtEmpReadOnly.Value = step.IsApprovalByEmpNull() ? "" : step.ApprovalByEmp;
        }

        private ApprovalStepDataSet GetFields(string id)
        {
            StepRow step = null;
            if (String.IsNullOrEmpty(id))
            {
                step = (new ApprovalStepDataSet()).ApprovalStep.NewApprovalStepRow();
                SiteUtil.PopulateCommonField(step, Guid.NewGuid());
            }
            else
            {
                // update
                step = CentralOffice.Admin.BusinessActions.ApprovalStep.GetByIdFromCache(new Guid(id));
            }
            step.ApprovalProcessId = new Guid(ddlApprovalProcess.SelectedItem.Value);
            step.Name = txtName.Text;
            step.StepOrder = txtStepOrder.Text.Length > 0 ? Int32.Parse(txtStepOrder.Text) : 0;
            //step.ApprovalObject = EnumUtil.GetInt32(SiteConstants.ApprovalObject, ddlApprovalObject.SelectedItem.Text);
            //if(ddlPreviousStep.Items.Count > 0)
            //{
            //    if (ddlPreviousStep.SelectedIndex > 0)
            //    {
            //        step.PreviousStepId = new Guid(ddlPreviousStep.SelectedItem.Value);
            //    }
            //}

            step.ApprovalBy = CommonUtil.InputText(txtRoles.Text);
            step.ApprovalContent = CommonUtil.InputText(txtContent.Text);
            step.ApprovalByEmp = txtEmp.Value;
            
            if (String.IsNullOrEmpty(id))
            {
                step.Table.Rows.Add(step);
            }

            return step.Table.DataSet as ApprovalStepDataSet;
        }

        protected void ddlApprovalObject_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindProcess(Int32.Parse(ddlApprovalObject.SelectedItem.Value));
            if (ddlApprovalProcess.SelectedItem != null)
            {
                BindStep(new Guid(ddlApprovalProcess.SelectedItem.Value));
            }
        }

        private void BindProcess(int approvalSubject)
        {
            PopulateProcess(approvalSubject);

            upApprovalProcess.Update();
        }

        private void PopulateProcess(int approvalSubject)
        {
            ProcessTable processes = CentralOffice.Admin.BusinessActions.ApprovalProcess.GetProcessBySubject(approvalSubject);

            ddlApprovalProcess.Items.Clear();
            ddlApprovalProcess.DataSource = processes;
            ddlApprovalProcess.DataTextField = "Name";
            ddlApprovalProcess.DataValueField = "Id";
            ddlApprovalProcess.DataBind();
        }

        protected void ddlApprovalProcess_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindStep(new Guid(ddlApprovalProcess.SelectedItem.Value));
        }

        private void PopulateStep(Guid processId)
        {
            //StepTable steps = CentralOffice.Admin.BusinessActions.ApprovalStep.GetStepByProcessId(processId);
            //SiteUtil.PopulateListBox(ddlPreviousStep, steps, "Id", "Name", true);
        }

        private void BindStep(Guid processId)
        {
            //PopulateStep(processId);
            //upPreviousStep.Update();
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            Save();

            Server.Transfer("ApprovalProcess.aspx");
        }

        private Guid Save()
        {
            string id = HttpContext.Current.Request.QueryString["id"];
            //String savePath = SiteUtil.GetDocumentFilePath();
            ApprovalStepDataSet step = GetFields(id);
            int cnt = CentralOffice.Admin.BusinessActions.ApprovalStep.Update(step);

            Guid stepId = (step.ApprovalStep.Rows[0] as StepRow).Id;

            return stepId;
        }

        protected void btnContinue_Click(object sender, EventArgs e)
        {
            Save();
            ClearFields();
        }

        private void ClearFields()
        {
            txtStepOrder.Text = "";
            txtName.Text = "";
            txtContent.Text = "";
            txtRoles.Text = "";

            txtEmpReadOnly.Value = "";
            txtEmp.Value = "";

        }

        protected void tvEmp_Load(object sender, EventArgs e)
        {
            this.tvEmp.Attributes.Add("OnClick", "OnTreeNodeChecked(event)");
        }

        protected void btnShowPopup_Click(object sender, EventArgs e)
        {
            string[] assignedBy = null; //txtApprovedBy.Value.Split(',');
            LinkButton btn = sender as LinkButton;
            if (btn != null)
            {
                assignedBy = txtEmp.Value.Split(',');
            }

            tvEmp.Nodes.Clear();
            //HumanResources.HumanResourcesHelper.PopulateEmployeeTree(tvEmp, true, assignedBy);
            HumanResources.HumanResourcesHelper.PopulateEmployeeTree(tvEmp, true, assignedBy);//null

            updPnlDepartment.Update();
            mdlDetailView.Show();
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            // 保存弹出窗口所更新的信息
            string employees = "";
            string employeesId = "";

            if (tvEmp.CheckedNodes.Count > 0)
            {
                foreach (TreeNode node in tvEmp.CheckedNodes)
                {
                    if (!node.Text.StartsWith("["))
                    {
                        employees += node.Text + ",";
                        employeesId += node.Value + ",";
                    }
                }
            }

            txtEmpReadOnly.Value = employees.Trim(',');
            txtEmp.Value = employees.Trim(',');
        }
    }
}